package com.webserver.core;

import com.webserver.http.HttpRequest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 该线程负责与指定客户端完成HTTP协议的交互过程
 *
 */
public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    public void run() {
        //测试:读取客户端发送过来的内容
        try {
            //1.解析请求
            HttpRequest request = new HttpRequest(socket);
            //2.处理请求
            String path = request.getUri();
            System.out.println("抽象路径为:"+path);
            File file = new File("./webapps"+path);
            //3.发送响应
            /*
                HTTP/1.1 200 OK(CRLF)
                Content-Type: text/html(CRLF)
                Content-Length: 2546(CRLF)(CRLF)
                1011101010101010101......
             */
            OutputStream out = socket.getOutputStream();



            //3.1发送状态行
            String line = "HTTP/1.1 200 OK";
            byte[] data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);//写回车符
            out.write(10);//写换行符

            //3.2发送响应头
            line = "Content-Type: text/html";
            data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);//写回车符
            out.write(10);//写换行符

            line = "Content-Length: "+file.length();
            data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);//写回车符
            out.write(10);//写换行符

            //单独发送CRLF表示响应头发送完毕
            out.write(13);//写回车符
            out.write(10);//写换行符

            //3.3发送响应正文
            //将文件数据发送给浏览器
            FileInputStream fis = new FileInputStream(file);
            data = new byte[1024*10];//10kb
            int len;
            while ((len = fis.read(data))!=-1){
                out.write(data,0,len);
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
